package cn.openea.perpartner.wxpay.service.impl;

import cn.openea.perpartner.wxpay.service.ReflectObject;
import cn.openea.perpartner.wxpay.vo.PayVo;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
import java.util.*;
/**
 * @Name: 反射服务工具实现类
 * @author: Mr.Yun
 * @Created: 2022/10/17 11:58
 */
@Service
public class ReflectObjectImpl implements ReflectObject {
    @Override
    public Map<String, Object> payVoToMap(PayVo payVo) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<? extends PayVo> clazz = payVo.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field: fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(payVo));
        }
        return map;
    }

    @Override
    public List<Field> getFieldList(Object object) {
        List<Field> fieldList = new ArrayList<>();
        Class<? extends Object> clazz = object.getClass();
        fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
        // 获取父类，并不断循环获取父类的父类的字段 https://www.jianshu.com/p/16ceb7240d9f
        Class superclazz = clazz.getSuperclass();
        while (superclazz != null) {
            // 将父类的字段添加到集合中
            fieldList.addAll(Arrays.asList(superclazz.getDeclaredFields()));
            // 获取父类的父类，如果为空就停止循环了
            superclazz = superclazz.getSuperclass();
        }
        return fieldList;
    }

    @Override
    public void invoke(Map map, Object object) throws IllegalAccessException {
        List<Field> fieldList = this.getFieldList(object);
        for (Field field: fieldList) {
            Object tmpvalue = map.get(field.getName());
            // 20221110 添加排除对序列字段进行赋值操作
            if(null != tmpvalue && !"serialVersionUID".equalsIgnoreCase(field.getName())){
                // 有多种方法进行赋值，可参考 https://blog.csdn.net/qidasheng2012/article/details/105056212
                field.setAccessible(true);
                field.set(object, tmpvalue);
            }
        }
    }
}
